"""
更新表名的迁移脚本
- schedule_results -> care_schedule_results
- time_slots -> care_time_slots
- shift_assignments -> care_shift_assignments
"""

import os
import sys
import logging
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 导入Flask应用
from app import create_app, db
from sqlalchemy import text

def update_table_names():
    """更新表名"""
    logger.info("开始更新表名...")

    # 创建Flask应用
    app = create_app()

    # 在应用上下文中执行迁移
    with app.app_context():
        try:
            # 检查新表是否已存在
            result = db.session.execute(text("SHOW TABLES LIKE 'care_schedule_results'"))
            if result.rowcount > 0:
                logger.info("care_schedule_results表已存在，无需更新")
            else:
                # 重命名schedule_results表
                db.session.execute(text("RENAME TABLE schedule_results TO care_schedule_results"))
                logger.info("成功将schedule_results表重命名为care_schedule_results")

            result = db.session.execute(text("SHOW TABLES LIKE 'care_time_slots'"))
            if result.rowcount > 0:
                logger.info("care_time_slots表已存在，无需更新")
            else:
                # 重命名time_slots表
                db.session.execute(text("RENAME TABLE time_slots TO care_time_slots"))
                logger.info("成功将time_slots表重命名为care_time_slots")

            result = db.session.execute(text("SHOW TABLES LIKE 'care_shift_assignments'"))
            if result.rowcount > 0:
                logger.info("care_shift_assignments表已存在，无需更新")
            else:
                # 重命名shift_assignments表
                db.session.execute(text("RENAME TABLE shift_assignments TO care_shift_assignments"))
                logger.info("成功将shift_assignments表重命名为care_shift_assignments")

            # 提交事务
            db.session.commit()
            logger.info("成功更新所有表名")
            
            return True
        except Exception as e:
            db.session.rollback()
            logger.error(f"更新表名时出错: {str(e)}")
            return False

if __name__ == "__main__":
    success = update_table_names()
    if success:
        print("成功更新表名")
    else:
        print("更新表名失败，请查看日志")
